package com.hai.udp;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;


/**
 * fileDesc
 * Created by huanghp on 2020/3/26.
 * Email h1132760021@sina.com
 */
public class MinaServer {
    public static void main(String[] args) {
        NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
        acceptor.setHandler(new MyHandler("服务器") {
            @Override
            public void messageReceived(IoSession session, Object message) throws Exception {
                super.messageReceived(session, message);
                System.out.println("recevie class=" + message.getClass().getSimpleName());
                session.write("这是服务器回复的消息");
            }
        });

        DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
//        chain.addLast("codec2", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("utf-8"))));
        chain.addLast("beanc2", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));

        DatagramSessionConfig dcfg = acceptor.getSessionConfig();
        dcfg.setReuseAddress(true);
        try {
            acceptor.bind(new InetSocketAddress(60030));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
